<?php 
class MpController extends SilkControllerBase {
	
	public function register( $params ) {
		if(!isset($params["redirect"])) {
			$params["redirect"] = SilkResponse::create_url(array("controller" => "dashboard"));
		}
		
		if(isset($params["input"])) {
			list($location_type, $location_id) = explode("_", $params["location_id"]);
			if($location_type != "city") {
				$this->set("error", "Please select a city for your location");
			} elseif($params["password"] == "") {
				$this->set("error", "Please enter a password");
			} elseif($params["password"] != $params["confirm_password"]) {
				$this->set("error", "Passwords do not match");
			} else {
				$regUser = new mpUser();
				$regUser->update_parameters($params);
				$regUser->status_id = 1;
				$regUser->last_login = new SilkDateTime();
				$regUser->location_id = $location_id;
				$regUser->set_password($params["password"]);
				$regUser->save();
				
				$group = orm("SilkGroup")->find_by_name("Users");
				$date = db()->DBTimeStamp(time());
				db()->Execute("INSERT INTO " . db_prefix() . "user_groups (user_id, group_id, create_date, modified_date) VALUES (?,?,{$date},{$date})", array($regUser->id, $group->id));
				
				$params["register"]["username"] = $params["username"];
				$params["register"]["password"] = $params["password"];
				
				$user_session = new SilkUserSession($params["register"]);
				
				if($user_session->login()) {
					redirect($params["redirect"]);
				} else {
					die("can't login");
				}
			}
		}
		
		$fields = array();
		$fields["gender"]["label"] = "Gender";
		$fields["gender"]["override"] = SilkForm::create_input_select(array("name" => "gender"));
		$fields["gender"]["override"].= SilkForm::create_input_options(array("items" => array("M" => "Male", "F" => "Female")));
		$fields["gender"]["override"].= SilkForm::create_end_tag("select");
		
		$items = array();
		$countries = orm("Country")->find_all(array("order" => "name ASC"));
		foreach($countries as $country) {
			$items["country_$country->id"] = $country->name;
			foreach($country->provinces as $province) {
				$items["province_$province->id"] = " -- $province->name";
				foreach($province->cities as $city) {
					$items["city_$city->id"] = " -- -- $city->name";
				}
			}
		}
		
		$fields["location_id"]["label"] = "Location";
		$fields["location_id"]["override"] = SilkForm::create_input_select(array("name" => "location_id"));
		$fields["location_id"]["override"].= SilkForm::create_input_options(array("items" => $items));
		$fields["location_id"]["override"].= SilkForm::create_end_tag("select");
		
		$fields["last_login"]["visible"] = "none";
		$this->set("fields", $fields);
		unset($params["input"]);
		unset($params["redirect"]);
		$this->set("params", $params);
	}
	
	public function ListSites( $params ) {
		echo "Listing sites<br />";
		$countries = orm('country')->find_all( array("order" => "name ASC",  'conditions'=>array("active = ?", 1) ) );
		$this->set( "countries", $countries );
	}
	public function PhotoOfTheMonth( $params ) {
		
	}
	public function FeaturedModel( $params ) {
		
	}
	public function Portfolio( $params ) {

		if( isset( $params["ajaxAction"] ) ) {
			
			$current_user = SilkUserSession::get_current_user();
			if(isset($current_user)) 
				$this->set("currentUserID", $current_user->id);
				
			return $this->run_ajax($params);
		}
		
		if(!isset($params["id"])) redirect(SilkResponse::create_url(array(	"controller" => "homepage",
																			"action" => "index"
																			)));
		$this->layout_name = 'extended';
		
		$current_user = SilkUserSession::get_current_user();
		if(isset($current_user)) 
			$this->set("currentUserID", $current_user->id);

		$portfolio = orm("Portfolio")->find_by_id( $params["id"] );
		$params["description"] = $portfolio->description;

		$this->set("experienceText", $portfolio->get_experience());
		$this->set( 'portfolio', $portfolio );
		$this->set( 'feedbacklimit', 3 );
		
		$params["ajaxAction"] = "edit";
		$this->set("params", $params);

	}
	
	public function editAboutMe_ajax($params) {
	    $this->show_layout = false;
		$resp = new SilkAjax();
		$params["ajaxAction"] = "save";
		$this->set("params", $params);
		
	    $resp->replace_html("#AboutMe", $this->render_partial("about_me_ajax.tpl"));
	    return $resp->get_result();
	}
	
	public function saveAboutMe_ajax($params) {
		$this->show_layout = false;
		$resp = new SilkAjax();
		$portfolio = orm("Portfolio")->find_by_id($params["id"]);
		$portfolio->description = $params["description"];
		$portfolio->save();
		
		$this->set("portfolio", $portfolio);
		$aboutMe = "<h4>Save successful</h4>";
		$params["ajaxAction"] = "edit";
		$this->set("params", $params);
		$aboutMe .= $this->render_partial("about_me_ajax.tpl");
		$resp->replace_html("#AboutMe", $aboutMe);
		return $resp->get_result();
	}
	
	public function editExperience_ajax($params) {
	    $this->set("experienceSelect", $this->experienceSelect($params["selected_value"]));
	    
	    $this->show_layout = false;
		$resp = new SilkAjax();
		$params["ajaxAction"] = "save";
		$this->set("params", $params);
	    $resp->replace_html("#experience", $this->render_partial("experience_ajax.tpl"));
	    return $resp->get_result();
	}
	
	public function saveExperience_ajax($params) {
		$this->show_layout = false;
		$resp = new SilkAjax();
		$portfolio = orm("portfolio")->find_by_id($params["id"]);
		$portfolio->experience_id = $params["experience"];
		$portfolio->save();
		$this->set("portfolio", $portfolio);
		
		$params["ajaxAction"] = "edit";
		$this->set("params", $params);
		$this->set("experienceText", $portfolio->get_experience($params["experience"]));
		$experience = $this->render_partial("experience_ajax.tpl");
		$resp->replace_html("#experience", $experience);
		return $resp->get_result();
	}
	
	public function experienceSelect($selected_value) {
		$experiences = orm("experience")->find_all(array("conditions" => array("status_id = ?", 1)));
		$select = SilkForm::create_input_select(array("name" => "experience"));
		
		$items = array();
		foreach($experiences as $key=>$value) {
			$items[$value->id] = $value->name;
		}
			$select .= SilkForm::create_input_options(array("items" => $items, "selected_value" => $selected_value));
		$select .= SilkForm::create_end_tag("select");
		return $select;
	}
	
	public function editWebsite_ajax($params) {
	    $this->show_layout = false;
		$resp = new SilkAjax();
		$params["ajaxAction"] = "save";
		$this->set("params", $params);
//		$portfolio = orm("portfolio")->find_by_id($params["id"]);
//		$this->set("portfolio", $portfolio);
	    $resp->replace_html("#website", $this->render_partial("website_ajax.tpl"));
	    return $resp->get_result();
	}
	
	public function saveWebsite_ajax($params) {
		$this->show_layout = false;
		$resp = new SilkAjax();
		$portfolio = orm("portfolio")->find_by_id($params["id"]);
		$portfolio->website_address = $params["website_address"];
		$portfolio->website_name = $params["website_name"];
		$portfolio->save();
		
		$params["ajaxAction"] = "edit";
		$this->set("params", $params);
		$this->set("portfolio", $portfolio);
	    $resp->replace_html("#website", $this->render_partial("website_ajax.tpl"));
		return $resp->get_result();

	}
	
	public function editInterests_ajax($params) {
	    $this->show_layout = false;
		$resp = new SilkAjax();
		$params["ajaxAction"] = "save";
		$this->set("params", $params);
		$this->set("interests", orm("interest")->find_all_by_status_id(1));
	    $resp->replace_html("#Interests", $this->render_partial("interests_ajax.tpl"));
	    return $resp->get_result();
	}
	
	public function saveInterests_ajax($params) {
//		echo "<pre>"; var_dump($params); echo "</pre>";
		$this->show_layout = false;
		$resp = new SilkAjax();
		
		//delete all interest prefs
		db()->Execute("DELETE FROM ". db_prefix() . "interests_vs_portfolios WHERE portfolio_id = $params[id]");
		foreach( $params as $key=>$value) {
			if( strpos( $key, "_" )) {
				list($i, $interest_id) = explode("_", $key);
				if( $i == "interest" ) {
					if( $value == "D" ) {
						// do nothing
					} else {
						$sql = "INSERT INTO " . db_prefix() . "interests_vs_portfolios (interest_id, portfolio_id, disposition) VALUES ($interest_id, $params[id], '$value'); ";
						db()->Execute($sql);
					}
					
				}
			}
		}

		$params["ajaxAction"] = "edit";
		$this->set("params", $params);
		$portfolio = orm("portfolio")->find_by_id($params["id"]);
		$this->set("portfolio", $portfolio);
	    $resp->replace_html("#Interests", $this->render_partial("interests_ajax.tpl"));
		return $resp->get_result();

	}
	
	/**
	 * Returns a user object and also sets it in the smarty template
	 *
	 * @param int $user_id
	 * @author Greg Froese
	 */
	public function get_user($user_id) {
		$user = orm("mp_user")->find_by_id($user_id);
		$this->set("user", $user);
		return $user;
	}
	
	public function get_portfolio( $params ) {
//		SilkGreg::barf("params", $params);
		$portfolio = orm(MpController::get_usertype_class_name( $params ) )->find_by_id( $params["portfolio_id"] );
		$this->set("portfolio", $portfolio);
		return $portfolio;
	}
	
	public function get_usertype_class_name($params) {
		$usertypes = orm("UserType")->find_all();
		foreach( $usertypes as $usertype ) {
			if( strtolower($usertype->class_name) == strtolower($params["type"])) {
				return $usertype->class_name;
			}
		}
		return null;
	}
	
	private function run_ajax( $params ) {
		$result = "";
		$this->show_layout = false;
		$this->set("params", $params);
		
		$portfolio = orm("Portfolio")->find_by_id($params["id"]);
		$this->set("portfolio", $portfolio);
//		SilkGreg::barf("params", $params); die;
		 
		switch( $params["element"] ) {
			case "aboutMe":
				switch( $params["ajaxAction"]) {
					case "edit":
						return $this->editAboutMe_ajax($params);
						break;
					case "save":
						return $this->saveAboutMe_ajax($params);
						break;
				}
			case "experience":
				switch( $params["ajaxAction"]) {
					case "edit":
						return $this->editExperience_ajax($params);
						break;
					case "save":
						return $this->saveExperience_ajax($params);
						break;
				}
			case "website":
				switch( $params["ajaxAction"]) {
					case "edit":
						return $this->editWebsite_ajax($params);
						break;
					case "save":
						return $this->saveWebsite_ajax($params);
						break;
				}
			case "interests":
				switch( $params["ajaxAction"]) {
					case "edit":
						return $this->editInterests_ajax($params);
						break;
					case "save":
						return $this->saveInterests_ajax($params);
						break;
				}
		}
		return $result;
	}
	
	public function ListSets( $params ) {
		
	}
	public function ListInterests( $params ) {
		$this->set( 'interests', $params['portfolio']->interests );
	}
	public function RecentFeedback( $params ) {
	}
	
	public function listCities( $params ) {
		$cities = orm("city")->find_all_by_status_id(1);
		return $cities;
	}
}
?>